﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using LiuYan.Entity;
using LiuYan.Interface;
using LiuYan.Service;


namespace LiuYan.Web.Controllers
{
    public class BaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (HttpContext.Session["wxuser"] == null)
            {

                TB_User entity = new TB_User();
                entity.Id = 10;
                entity.Img = "http://wx.qlogo.cn/mmopen/bofA1vl6EUYZZBmUWLxhBIUIia7ibZf4dkNBOWfEMGibkibuEVC6Xjm34miaj36fO86lQpHTwUDHuGBRrnUCiaDIGDztetNw0XaaDl/0";
                entity.NcName = "天还很蓝";
                entity.OpenId = "dsghsdrwerthsargds";
                entity.Sex = 1;
                entity.Tell = "1244";
                HttpContext.Session["wxuser"] = entity;
            }
            //Session["url"] = Request.Url.ToString();
            //if (HttpContext.Session["wxuser"] == null)
            //{
            //    if (Request["code"] == null)
            //    {//oauth授权
            //        var sq = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WxEntity.appid + "&redirect_uri=" + Session["url"] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            //        Response.Redirect(sq);
            //    }
            //    else
            //    {
            //        try
            //        {
            //            var code = Request["code"];
            //            var url = string.Format(WxEntity.GetOpenIdUrl, WxEntity.appid, WxEntity.secret, code);
            //            string temp = "";
            //            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //            using (Stream resStream = response.GetResponseStream())
            //            {
            //                StreamReader reader = new StreamReader(resStream, Encoding.Default);
            //                temp = reader.ReadToEnd();
            //                resStream.Close();
            //            }
            //            WriteMess("temp:" + temp);
            //            JavaScriptSerializer Jss = new JavaScriptSerializer();
            //            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(temp);
            //            WriteMess("entity:" + respDic["openid"].ToString());
            //            TB_User entity = new UserService().Login(respDic["openid"].ToString());
            //            WriteMess("entity:" + entity.Id);
            //            if (entity.Id == 0)
            //            {
            //                string openid = respDic["openid"].ToString();
            //                string access_token = respDic["access_token"].ToString();
            //                GetWxUser(access_token, openid);
            //            }
            //            else
            //            {
            //                HttpContext.Session["wxuser"] = entity;
            //            }
            //        }
            //        catch (Exception e)
            //        {
            //            WriteMess("Exception:" + e.ToString());
            //            Response.Redirect(WxEntity.OauthUrl);
            //        }
              //  }
            //}
        }
        public void GetWxUser(string accesstoken, string openid)
        {
            try
            {
                string temp = "";
                WxEntity.getAccessTokenUrl = string.Format(WxEntity.GetWxUserUrl, accesstoken, openid);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WxEntity.getAccessTokenUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream resStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(resStream, Encoding.GetEncoding("UTF-8"));
                    temp = reader.ReadToEnd();
                    resStream.Close();
                }
                JavaScriptSerializer Jss = new JavaScriptSerializer();
                Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(temp);
                //  WriteMess("user:" + temp);
                //openid = respDic["openid"].ToString();
                //string nickname = respDic["nickname"].ToString();
                //string sex = respDic["sex"].ToString();
                //string country = respDic["country"].ToString();
                //string headimgurl = respDic["headimgurl"].ToString();
                //var str = "<label style=\"font-size:20px;\">微信唯一Id:" + openid + "</label></br>";
                //str += "<label style=\"font-size:20px;\">昵称:" + nickname + "</label></br>";
                //str += "<label style=\"font-size:20px;\">性别:" + (sex == "1" ? "男" : "女") + "</label></br>";
                //str += "<label style=\"font-size:20px;\">国家:" + country + "</label></br>";
                //str += "<label style=\"font-size:20px;\">头像:</label></br>";
                //str += "<img src=" + headimgurl + " width='100' height='100'/></br>";
                //WriteMess(str);
                TB_User entity = new TB_User();
                entity.Id = 0;
                entity.Img = respDic["headimgurl"].ToString();
                entity.NcName = respDic["nickname"].ToString();
                entity.OpenId = respDic["openid"].ToString();
                entity.Sex = Convert.ToInt32(respDic["sex"].ToString());
                entity.Tell = "";
                entity.Name = "";
                new UserService().Edit(entity);
                TB_User entity1 = new UserService().Login(respDic["openid"].ToString());
                HttpContext.Session["wxuser"] = entity1;
            }
            catch (Exception e)
            {
                //  WriteMess(e.ToString()); 
            }

        }

        /// <summary>
        /// 获取会员信息
        /// </summary>
        /// <returns></returns>
        public TB_User UserInfo()
        {
            return (HttpContext.Session["wxuser"] as TB_User);
        }

        public void WriteMess(string mess)
        {

            string realPath = Server.MapPath("//rizhi.txt");//真正的地址
            FileStream fsWriter = null;//公开以文件为主的流
            if (!System.IO.File.Exists(realPath))
            {
                fsWriter = new FileStream(realPath, FileMode.Create);
            }
            else
            {
                fsWriter = new FileStream(realPath, FileMode.Append);
            }
            StreamWriter sw = new StreamWriter(fsWriter);//实现一个类，向流中写入字符
            sw.WriteLine(mess);//写入流
            sw.Close();//类关闭
            fsWriter.Close();//流关闭
        }

    }
}
